/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.netbrain.util;

import java.io.File;
import java.io.Serializable;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import mx.netbrain.dao.TreeDao;
import mx.netbrain.dao.impl.TreeDaoImpl;
import mx.netbrain.model.Status;
import mx.netbrain.model.Tree;
import mx.netbrain.model.User;

/**
 * 
 * @author gamma
 */
public class CreateFolderUtil implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -127834506080216149L;
	private static char sep = File.separatorChar;

	public static boolean createFolderUtil(String route) {
		if (!route.substring(0, route.length() - 1).equals(sep)) {
			route = route + sep;
		}
		File folder = new File(route);
		if (folder.mkdirs()) {
			return true;
		} else {
			return false;
		}
	}

	public static void createFolderDataBase(Tree tree, String name, User user,
			Long perfil) {
		Tree treeNew = new Tree();
		TreeDao treeDaoNew = new TreeDaoImpl();
		if (treeDaoNew.findTreeName(name, tree.getId())) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Error",
					"Ya existe una carpeta con el nombre: " + name);
			FacesContext.getCurrentInstance().addMessage(null, message);
		} else {
			treeNew.setName(name);
			treeNew.setRoute(tree.getRoute() + sep + treeNew.getId() + sep);
			treeNew.setRoot(tree.getId());
			treeNew.setType("Carpeta");
			treeNew.setRegister(new Date());
			treeNew.setRepositories(tree.getRepositories());
			treeNew.setUser(user);
			treeDaoNew.save(treeNew);
			treeNew.setRoute(tree.getRoute() + treeNew.getId() + sep);
			createFolderUtil(tree.getRoute() + treeNew.getId());
			treeDaoNew.update(treeNew);
		}
	}

	public static void editFolderDataBase(Tree tree) {
		TreeDao treeDaoNew = new TreeDaoImpl();
		treeDaoNew.update(tree);
	}

	public static void deleteFolderDataBase(Tree tree) {
		Status status = new Status();
		status.setId(2);
		tree.setStatus(status);
		TreeDao treeDaoNew = new TreeDaoImpl();
		treeDaoNew.update(tree);
	}
}
